<!--
  智慧社区管理系统 - 费用生成弹窗组件
  @author Wu.Liang
  @date 2024-12-21
  @updated 2025-01-30 - 去掉费用类型和费用输入部分，后台根据计费方式自动计算
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="生成费用账单"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      @submit.prevent="handleSubmit"
    >
      <el-form-item label="选择社区" prop="communityId">
        <el-select
          v-model="form.communityId"
          placeholder="请选择社区"
          style="width: 100%"
          @change="handleCommunityChange"
        >
          <el-option
            v-for="item in communityList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="计费月份时间段" prop="billingMonthRange">
        <el-date-picker
          v-model="form.billingMonthRange"
          type="monthrange"
          placeholder="请选择计费月份时间段"
          format="YYYY-MM"
          value-format="YYYY-MM"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="到期日期" prop="dueDate">
        <el-date-picker
          v-model="form.dueDate"
          type="date"
          placeholder="请选择到期日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="生成范围">
        <el-radio-group v-model="form.generateType">
          <el-radio value="ALL">全部房户</el-radio>
          <el-radio value="SELECTED">指定楼栋</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        v-if="form.generateType === 'SELECTED'"
        label="选择楼栋"
        prop="buildingIds"
      >
        <el-select
          v-model="form.buildingIds"
          multiple
          placeholder="请选择楼栋"
          style="width: 100%"
        >
          <el-option
            v-for="item in buildingList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          确认生成
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { buildingApi } from '@/api/building'
import { regionApi } from '@/api/region'
import { showError } from '@/utils/message'

// Props
interface Props {
  modelValue: boolean
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [data: any]
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const communityList = ref<any[]>([])
const buildingList = ref<any[]>([])

// 表单数据
const form = reactive<{
  communityId: number | undefined | null
  billingMonthRange: string[] | undefined | null
  dueDate: string | undefined | null
  generateType: 'ALL' | 'SELECTED'
  buildingIds: number[] | undefined | null
  remark?: string
}>({
  communityId: undefined,
  billingMonthRange: undefined,
  dueDate: undefined,
  generateType: 'ALL',
  buildingIds: undefined,
  remark: ''
})

// 校验规则
const rules: FormRules = {
  communityId: [
    { required: true, message: '请选择社区', trigger: 'change' }
  ],
  billingMonthRange: [
    { type: 'array', required: true, message: '请选择计费月份时间段', trigger: 'change' }
  ],
  dueDate: [
    { required: true, message: '请选择到期日期', trigger: 'change' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听器
watch(() => form.communityId, (newVal) => {
  if (newVal) {
    loadBuildingList(newVal)
  } else {
    buildingList.value = []
    form.buildingIds = []
  }
})

// 生命周期
const loadCommunityList = async () => {
  try {
    const response = await regionApi.getCommunityList()
    if (response.success) {
      communityList.value = response.data
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
    showError('加载社区列表失败')
  }
}

const loadBuildingList = async (communityId: number) => {
  try {
    const response = await buildingApi.getBuildingsByCommunity(communityId)
    if (response.data) {
      buildingList.value = response.data
    }
  } catch (error) {
    console.error('加载楼栋列表失败:', error)
    showError('加载楼栋列表失败')
  }
}

// 事件处理
const handleCommunityChange = () => {
  form.buildingIds = []
  buildingList.value = []
}

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    if (!form.communityId) {
      ElMessage.error('请选择社区')
      return
    }
    if (!form.billingMonthRange || form.billingMonthRange.length !== 2) {
      ElMessage.error('请选择计费月份时间段')
      return
    }
    if (!form.dueDate) {
      ElMessage.error('请选择到期日期')
      return
    }
    
    // 提交数据 - 不再包含费用类型和费用金额，后台会根据计费方式自动计算
    const submitData: any = {
      communityId: form.communityId,
      billingMonthRange: form.billingMonthRange,
      dueDate: form.dueDate,
      ...(form.remark && { remark: form.remark })
    }
    emit('confirm', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    communityId: undefined,
    billingMonthRange: undefined,
    dueDate: undefined,
    generateType: 'ALL',
    buildingIds: undefined,
    remark: ''
  })
}

// 初始化
loadCommunityList()
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style> 